<?php
/**
 * Aes 的加密与解密
 */

namespace PKFrame\Lib;

class Aes
{
    private $iv = '0102030405060708'; // 偏移量 16
    private $key = '1234567891234567'; // 密码 随便
    private $cipher_methods = 'aes-128-cbc';

    protected function checkCipherMethods()
    {
        in_array($this->cipher_methods,openssl_get_cipher_methods(true))
            ?: out()->notice('The method of obtaining the password is not within the support range of OpenSSL');
    }

    // 加密
    /**
     * @param $str
     * @return string
     */
    public function encrtyp($str): string
    {
        $this->checkCipherMethods();
        $data = openssl_encrypt($str, $this->cipher_methods, $this->key, OPENSSL_RAW_DATA, $this->iv);
        return base64_encode($data);
    }

    /**
     * 解密
     * @param $str
     * @return false|string
     */
    public function decrtyp($str)
    {
        $this->checkCipherMethods();
        $data = base64_decode($str);
        return openssl_decrypt($data, $this->cipher_methods, $this->key, OPENSSL_RAW_DATA, $this->iv);
    }

    /**
     * @param string $iv
     * @return Aes
     */
    public function setIv(string $iv): Aes
    {
        $this->iv = $iv;
        return $this;
    }

    /**
     * @param string $key
     * @return Aes
     */
    public function setKey(string $key): Aes
    {
        $this->key = $key;
        return $this;
    }

    /**
     * @return Aes
     */
    public function setCipherMethodsOfRands(): Aes
    {
        $methods_list = openssl_get_cipher_methods(true);
        $methods_size = count($methods_list);
        $rand_size = ceil(rand(0,$methods_size));
        $this->cipher_methods = $methods_list[$rand_size];
        return $this;
    }

    /**
     * @return string
     */
    public function getCipherMethods(): string
    {
        return $this->cipher_methods;
    }

    /**
     * @param string $cipher_methods
     * @return $this
     */
    public function setCipherMethods(string $cipher_methods): Aes
    {
        $this->cipher_methods = $cipher_methods;
        return $this;
    }
}